package com.css.fxfzysx.modules.vabStructure.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzysx.base.response.RestResponse;
import com.css.fxfzysx.common.utils.BeanUtil;
import com.css.fxfzysx.constants.FxfzConstants;
import com.css.fxfzysx.modules.cztDataMange.constans.RedisKeyConstants;
import com.css.fxfzysx.modules.cztDataMange.entity.CbhdInfoEntity;
import com.css.fxfzysx.modules.cztDataMange.service.impl.SdoBuildingsServiceImpl;
import com.css.fxfzysx.modules.cztDataMange.utils.GenerationNumberUtil;
import com.css.fxfzysx.modules.vabStructure.entity.CztBuildingMatrixEntity;
import com.css.fxfzysx.modules.vabStructure.param.BuildingStructureParam;
import com.css.fxfzysx.modules.vabStructure.param.CustomVulnerabilityParam;
import com.css.fxfzysx.modules.vabStructure.param.ModelCalculationParam;
import com.css.fxfzysx.modules.vabStructure.repository.CustomVulnerabilityRepository;
import com.css.fxfzysx.modules.vabStructure.repository.SvAnalysisRepository;
import com.css.fxfzysx.modules.vabStructure.service.SvAnalysisService;
import com.css.fxfzysx.modules.vabStructure.vo.GenerateVulnerabilityMatrixVo;
import com.css.fxfzysx.util.*;
import com.css.fxfzysx.web.PlatformSessionContext;
import com.css.fxfzysx.zcpt.sys.entity.SUser;
import com.css.fxfzysx.zcpt.sys.service.SUserService;
import com.css.fxfzysx.zcpt.sys.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SvAnalysisServiceImpl implements SvAnalysisService {

    @Autowired
    private SvAnalysisRepository svAnalysisRepository;

    @Autowired
    private SysRoleService roleService;

    @Resource
    private GenerationNumberUtil generationNumberUtil;

    @Autowired
    private SdoBuildingsServiceImpl sdoBuildingsService;

    @Autowired
    private FshBuildingsServiceImpl fshBuildingsService;

    @Autowired
    private PobStructureServiceImpl pobStructureService;

    @Autowired
    private SrcAnalyseServiceImpl srcAnalyseService;

    @Autowired
    private CustomVulnerabilityRepository customVulnerabilityRepository;

    @Autowired
    private SUserService userService;



    @Override
    public RestResponse generateVulnerabilityMatrix(String ids, Integer type) {
        try {
            HashMap<String, Object> map = new HashMap<>();
            String newIds = spilt(ids);
            CztBuildingMatrixEntity cztBuildingMatrixEntity = null;
            String[] intensityArr = {"6度", "7度", "8度", "9度", "10度"};
            List<GenerateVulnerabilityMatrixVo> dataList = new ArrayList<>();
            //查询是否生成矩阵了
            if (!getBuildingMatrix(ids)) {
                return RestResponse.fail("失败! 该数据已经生成矩阵,请勿重复生成");
            }
            //震害数据矩阵
            List<CbhdInfoEntity> list = svAnalysisRepository.getEarthquakeDamageData(newIds, type);
            if (type == 1) {
                dataList = getDataList(newIds, intensityArr);
            }
            // 2 预测数据矩阵  3 筛选数据矩阵
            if (type == 2 || type == 3) {
                dataList = getPredictiveData(newIds, intensityArr, type);
            }
            cztBuildingMatrixEntity = saveBuildingMatrix(ids, type, list);
            map.put("data", dataList);
            map.put("id", cztBuildingMatrixEntity);
            return RestResponse.succeed(map);
        } catch (Exception e) {
            String errorMessage = "失败,请确保选中数据已经计算!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    /**
     * 校验数据是否符合规范   （6-10度都存在，都不少于30。有一个少于30，就提示“样本数据不足，分析结果慎用！”）
     *
     * @param list
     * @return
     */
    private boolean specification(List<CbhdInfoEntity> list) {
        Map<String, Long> collect = list.stream().collect(Collectors.groupingBy(CbhdInfoEntity::getIntensity, Collectors.counting()));
        AtomicBoolean specification = new AtomicBoolean(true);
        if (collect.size() < 5) {
            specification.set(false);
        }
        collect.forEach((intensity, count) -> {
            //6-10度都存在，都不少于30。有一个少于30，就提示“样本数据不足，分析结果慎用！
            //240309 改为50条
            if (count < 50) {
                specification.set(false);
            }
        });
        return specification.get();
    }

    private boolean getBuildingMatrix(String ids) {
        Integer count = svAnalysisRepository.getBuildingMatrix(ids);
        if (count == 0) {
            return true;
        } else {
            return false;
        }
    }

    public CztBuildingMatrixEntity saveBuildingMatrix(String ids, Integer type, List<CbhdInfoEntity> list) {
        CztBuildingMatrixEntity cztBuildingMatrix = new CztBuildingMatrixEntity();

        if (list.size() == 1) {
            BeanUtil.copyPropertiesIgnoreEmpty(list.get(0), cztBuildingMatrix);
        }
        if (PlatformObjectUtils.isNotEmpty(list)) {
            CbhdInfoEntity entity = list.get(0);
            // 依次与后面的对象比较字段值
            for (int i = 1; i < list.size(); i++) {
                CbhdInfoEntity entity1 = list.get(i);
                if (!entity1.getProvince().equals(entity.getProvince())) {
                    cztBuildingMatrix.setProvince("-");
                } else {
                    cztBuildingMatrix.setProvince(entity1.getProvince());
                }

                if (!entity1.getCity().equals(entity.getCity())) {
                    cztBuildingMatrix.setCity("-");
                } else {
                    cztBuildingMatrix.setCity(entity1.getCity());
                }

                if (!entity1.getCounty().equals(entity.getCounty())) {
                    cztBuildingMatrix.setCounty("-");
                } else {
                    cztBuildingMatrix.setCounty(entity1.getCounty());
                }

                if (!entity1.getStructureType().equals(entity.getStructureType())) {
                    cztBuildingMatrix.setStructureType("-");
                } else {
                    cztBuildingMatrix.setStructureType(entity1.getStructureType());
                }

                if (!entity1.getStructureType1().equals(entity.getStructureType1())) {
                    cztBuildingMatrix.setStructureType1("-");
                } else {
                    cztBuildingMatrix.setStructureType1(entity1.getStructureType1());
                }

                if (!entity1.getYears().equals(entity.getYears())) {
                    cztBuildingMatrix.setYears("-");
                } else {
                    cztBuildingMatrix.setYears(entity1.getYears());
                }

                if (!entity1.getFortification().equals(entity.getFortification())) {
                    cztBuildingMatrix.setFortification("-");
                } else {
                    cztBuildingMatrix.setFortification(entity1.getFortification());
                }

                if (!entity1.getCs().equals(entity.getCs())) {
                    cztBuildingMatrix.setCs("-");
                } else {
                    cztBuildingMatrix.setCs(entity1.getCs());
                }

                if (!entity1.getUse0().equals(entity.getUse0())) {
                    cztBuildingMatrix.setUse0("-");
                } else {
                    cztBuildingMatrix.setUse0(entity1.getUse0());
                }

                if (!entity1.getUse1().equals(entity.getUse1())) {
                    cztBuildingMatrix.setUse1("-");
                } else {
                    cztBuildingMatrix.setUse1(entity1.getUse1());
                }
            }
        }
        String numbers = list.stream()
                .map(CbhdInfoEntity::getNumber)
                .distinct()
                .collect(Collectors.joining(","));
        cztBuildingMatrix.setDataSourcesNums(numbers);
        cztBuildingMatrix.setNumber("ZHTJ" + "-" + generationNumberUtil.getGenerationNumber(RedisKeyConstants.CZT_ZHTJ_KEY));
        cztBuildingMatrix.setCreateUser(PlatformSessionContext.getUserID());
        cztBuildingMatrix.setMatrixId(UUIDGenerator.getUUID());
        cztBuildingMatrix.setDataType(FxfzConstants.CZT_SCYSX_INFO);
        cztBuildingMatrix.setMatrixType(type);
        cztBuildingMatrix.setIsSpecification(specification(list) ? "0" : "1");
        cztBuildingMatrix.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        cztBuildingMatrix.setBasicLibrary("0");
        cztBuildingMatrix.setDelFlag("0");
        cztBuildingMatrix.setDataSourcesIds(ids);
        String user = userService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        cztBuildingMatrix.setUserName(sUser.getUserName());
        svAnalysisRepository.saveBuildingMatrix(cztBuildingMatrix);
        return cztBuildingMatrix;
    }

    public List<GenerateVulnerabilityMatrixVo> getPredictiveData(String ids, String[] intensityArr, Integer type) {
        ArrayList<GenerateVulnerabilityMatrixVo> resultList = new ArrayList<>();
        for (String intensity : intensityArr) {
            List<GenerateVulnerabilityMatrixVo> dataList = svAnalysisRepository.getDataPredictiveByNumbers(ids, intensity, type);
            dataList.forEach(it -> {
                if (PlatformObjectUtils.isNotEmpty(it.getDamage()) && it.getDamage().equals("完好")) {
                    it.setDamage("基本完好");
                }
                if (PlatformObjectUtils.isNotEmpty(it.getDamage()) && it.getDamage().equals("毁坏")) {
                    it.setDamage("倒塌");
                }
                it.setIntensity(intensity);
                resultList.add(it);
            });
            if (resultList.stream().noneMatch(obj -> "基本完好".equals(obj.getDamage()) && intensity.equals(obj.getIntensity()))) {
                GenerateVulnerabilityMatrixVo entity = new GenerateVulnerabilityMatrixVo();
                entity.setDamage("基本完好");
                entity.setRate("0%");
                entity.setIntensity(intensity);
                resultList.add(entity);
            }
            if (resultList.stream().noneMatch(obj -> "轻微破坏".equals(obj.getDamage()) && intensity.equals(obj.getIntensity()))) {
                GenerateVulnerabilityMatrixVo entity = new GenerateVulnerabilityMatrixVo();
                entity.setDamage("轻微破坏");
                entity.setRate("0%");
                entity.setIntensity(intensity);
                resultList.add(entity);
            }
            if (resultList.stream().noneMatch(obj -> "中等破坏".equals(obj.getDamage()) && intensity.equals(obj.getIntensity()))) {
                GenerateVulnerabilityMatrixVo entity = new GenerateVulnerabilityMatrixVo();
                entity.setDamage("中等破坏");
                entity.setRate("0%");
                entity.setIntensity(intensity);
                resultList.add(entity);
            }
            if (resultList.stream().noneMatch(obj -> "严重破坏".equals(obj.getDamage()) && intensity.equals(obj.getIntensity()))){
                GenerateVulnerabilityMatrixVo entity = new GenerateVulnerabilityMatrixVo();
                entity.setDamage("严重破坏");
                entity.setRate("0%");
                entity.setIntensity(intensity);
                resultList.add(entity);
            }
            if (resultList.stream().noneMatch(obj -> "倒塌".equals(obj.getDamage()) && intensity.equals(obj.getIntensity()))) {
                GenerateVulnerabilityMatrixVo entity = new GenerateVulnerabilityMatrixVo();
                entity.setDamage("倒塌");
                entity.setRate("0%");
                entity.setIntensity(intensity);
                resultList.add(entity);
            }
        }
        return resultList;
    }

    public List<GenerateVulnerabilityMatrixVo> getDataList(String ids, String[] intensityArr) {
        ArrayList<GenerateVulnerabilityMatrixVo> resultList = new ArrayList<>();
        for (String intensity : intensityArr) {
            List<GenerateVulnerabilityMatrixVo> dataList = svAnalysisRepository.getDataPercentageByNumbers(ids, intensity);
            if (dataList.size() != 0) {
                dataList.forEach(it -> {
                    it.setIntensity(intensity);
                    resultList.add(it);
                });
                if (dataList.stream().noneMatch(obj -> "基本完好".equals(obj.getDamage()) && intensity.equals(obj.getIntensity()))) {
                    GenerateVulnerabilityMatrixVo entity = new GenerateVulnerabilityMatrixVo();
                    entity.setDamage("基本完好");
                    entity.setRate("0%");
                    entity.setIntensity(intensity);
                    resultList.add(entity);
                }
                if (dataList.stream().noneMatch(obj -> "轻微破坏".equals(obj.getDamage()) && intensity.equals(obj.getIntensity()))) {
                    GenerateVulnerabilityMatrixVo entity = new GenerateVulnerabilityMatrixVo();
                    entity.setDamage("轻微破坏");
                    entity.setRate("0%");
                    entity.setIntensity(intensity);
                    resultList.add(entity);
                }
                if (dataList.stream().noneMatch(obj -> "中等破坏".equals(obj.getDamage()) && intensity.equals(obj.getIntensity()))) {
                    GenerateVulnerabilityMatrixVo entity = new GenerateVulnerabilityMatrixVo();
                    entity.setDamage("中等破坏");
                    entity.setRate("0%");
                    entity.setIntensity(intensity);
                    resultList.add(entity);
                }
                if (dataList.stream().noneMatch(obj -> "严重破坏".equals(obj.getDamage()) && intensity.equals(obj.getIntensity()))) {
                    GenerateVulnerabilityMatrixVo entity = new GenerateVulnerabilityMatrixVo();
                    entity.setDamage("严重破坏");
                    entity.setRate("0%");
                    entity.setIntensity(intensity);
                    resultList.add(entity);
                }
                if (dataList.stream().noneMatch(obj -> "倒塌".equals(obj.getDamage()) && intensity.equals(obj.getIntensity()))) {
                    GenerateVulnerabilityMatrixVo entity = new GenerateVulnerabilityMatrixVo();
                    entity.setDamage("倒塌");
                    entity.setRate("0%");
                    entity.setIntensity(intensity);
                    resultList.add(entity);
                }
            }
        }
        return resultList;
    }

    public void exportMatrixUtil(HttpServletResponse response, List<GenerateVulnerabilityMatrixVo> dataList) {
        List<String> rowHead = CollUtil.newArrayList("烈度", "破坏程度", "百分比");
        ExcelWriter writer = ExcelUtil.getBigWriter();
        writer.writeHeadRow(rowHead);
        ServletOutputStream out = null;
        try {
            List<List<Object>> rows = new LinkedList<>();
            LinkedHashMap<String, List<GenerateVulnerabilityMatrixVo>> collect = dataList.stream().collect(Collectors.groupingBy(item -> item.getIntensity(),
                    LinkedHashMap::new, Collectors.toList()));
            int indexIntensity = 1;
            for (Map.Entry<String, List<GenerateVulnerabilityMatrixVo>> gvm : collect.entrySet()) {
                List<GenerateVulnerabilityMatrixVo> value = gvm.getValue();
                int size = value.size();
                if (size == 1) {
                    indexIntensity += size;
                } else {
                    writer.merge(indexIntensity, indexIntensity + size - 1, 0, 0, null, true);
                    indexIntensity += size;
                }
                value.forEach(
                        sList -> {
                            List<Object> rowA = null;
                            rowA = CollUtil.newArrayList(
                                    sList.getIntensity(),
                                    sList.getDamage(),
                                    sList.getRate()
                            );
                            rows.add(rowA);
                        }
                );
            }
            writer.write(rows, true);
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode("易损性矩阵信息", "utf-8") + ".xlsx");
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            IoUtil.close(out);
            writer.close();
        }
    }

    @Override
    public void exportMatrix(String ids, HttpServletResponse response, Integer type) {
        String numbers = spilt(ids);
        String[] intensityArr = {"6度", "7度", "8度", "9度", "10度"};
        List<GenerateVulnerabilityMatrixVo> dataList = new ArrayList<>();
        if (type == 1) {
            dataList = getDataList(numbers, intensityArr);
        }
        if (type == 2 || type == 3) {
            dataList = getPredictiveData(numbers, intensityArr, type);
        }
        exportMatrixUtil(response, dataList);
    }

    /**
     * 字符串逗号分隔加引号
     *
     * @param str
     * @return
     */
    public static String spilt(String str) {
        StringBuffer sb = new StringBuffer();
        String[] temp = str.split(",");
        for (int i = 0; i < temp.length; i++) {
            if (!"".equals(temp[i]) && temp[i] != null)
                sb.append("'" + temp[i] + "',");
        }
        String result = sb.toString();
        String tp = result.substring(result.length() - 1, result.length());
        if (",".equals(tp)) {
            return result.substring(0, result.length() - 1);
        } else {
            return result;
        }
    }

    @Override
    public RestResponse queryBuildings(CbhdInfoEntity cbhdInfoEntity, HttpServletRequest request) {
        try {
            int page = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int size = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            String userID = PlatformSessionContext.getUserID();
            String role = roleService.getRoleByUserId(userID);
            List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
            for (Map roleMap : roleMaps) {
                String roleCode = (String) roleMap.get("roleCode");
                if (roleCode.equals(FxfzConstants.CZT_PRI_GL_ROLE) || roleCode.equals(FxfzConstants.CZT_COUN_GL_ROLE)) {
                    cbhdInfoEntity.setRole("0");
                } else {
                    cbhdInfoEntity.setRole("1");
                }
            }
            return RestResponse.succeed(svAnalysisRepository.queryBuildings(cbhdInfoEntity, page, size));
        } catch (Exception e) {
            String errorMessage = "查看失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse queryBuildingStructure(BuildingStructureParam buildingStructureParam) {
        try {
            return RestResponse.succeed(svAnalysisRepository.queryBuildingStructure(buildingStructureParam));
        } catch (Exception e) {
            String errorMessage = "查看失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse queryPredictiveData(CbhdInfoEntity cbhdInfoEntity, HttpServletRequest request) {
        try {
            int page = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int size = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            String userID = PlatformSessionContext.getUserID();
            String role = roleService.getRoleByUserId(userID);
            List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
            for (Map roleMap : roleMaps) {
                String roleCode = (String) roleMap.get("roleCode");
                if (roleCode.equals(FxfzConstants.CZT_PRI_GL_ROLE) || roleCode.equals(FxfzConstants.CZT_COUN_GL_ROLE)) {
                    cbhdInfoEntity.setRole("0");
                } else {
                    cbhdInfoEntity.setRole("1");
                }
            }
            return RestResponse.succeed(svAnalysisRepository.queryPredictiveData(cbhdInfoEntity, page, size));
        } catch (Exception e) {
            String errorMessage = "查看失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse queryFilterData(CbhdInfoEntity cbhdInfoEntity, HttpServletRequest request) {
        try {
            int page = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int size = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            String userID = PlatformSessionContext.getUserID();
            String role = roleService.getRoleByUserId(userID);
            List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
            for (Map roleMap : roleMaps) {
                String roleCode = (String) roleMap.get("roleCode");
                if (roleCode.equals(FxfzConstants.CZT_PRI_GL_ROLE) || roleCode.equals(FxfzConstants.CZT_COUN_GL_ROLE)) {
                    cbhdInfoEntity.setRole("0");
                } else {
                    cbhdInfoEntity.setRole("1");
                }
            }
            return RestResponse.succeed(svAnalysisRepository.queryFilterData(cbhdInfoEntity, page, size));
        } catch (Exception e) {
            String errorMessage = "查看失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public boolean queryAdmin() {
        try {
            String userID = PlatformSessionContext.getUserID();
            String role = roleService.getRoleByUserId(userID);
            ArrayList<String> roleList = new ArrayList<>();
            List<Map> roleMaps = JSONObject.parseArray(URLDecoder.decode(role, "UTF-8"), Map.class);
            for (Map roleMap : roleMaps) {
                String roleCode = (String) roleMap.get("roleCode");
                roleList.add(roleCode);
            }
            return roleList.contains(FxfzConstants.CZT_COUN_GL_ROLE);
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    @Override
    public RestResponse getVulnerabilityMatrix(CztBuildingMatrixEntity cztBuildingMatrixEntity, HttpServletRequest
            request) {
        try {
            int page = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int size = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            return RestResponse.succeed(svAnalysisRepository.getVulnerabilityMatrix(cztBuildingMatrixEntity, page, size));
        } catch (Exception e) {
            String errorMessage = "查看失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse matrix(String matrixId) {
        try {
            CztBuildingMatrixEntity cztBuildingMatrixEntity = svAnalysisRepository.getBuildingMatrixById(matrixId);
            String spilt = spilt(cztBuildingMatrixEntity.getDataSourcesIds());
            String[] intensityArr = {"6度", "7度", "8度", "9度", "10度"};
            List<GenerateVulnerabilityMatrixVo> dataList = new ArrayList<>();
            //震害数据矩阵
            if (cztBuildingMatrixEntity.getMatrixType() == 1) {
                dataList = getDataList(spilt, intensityArr);
            }
            // 2 预测数据矩阵  3 筛选数据矩阵
            if (cztBuildingMatrixEntity.getMatrixType() == 2 || cztBuildingMatrixEntity.getMatrixType() == 3) {
                dataList = getPredictiveData(spilt, intensityArr, cztBuildingMatrixEntity.getMatrixType());
            }
            return RestResponse.succeed(dataList);
        } catch (Exception e) {
            String errorMessage = "失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse getDataById(String dataId, String dataType, String number) {
        RestResponse res = null;
        if (dataType.equals(FxfzConstants.CZT_LSZH_INFO)) {
            //这里是根据编号查询
            res = sdoBuildingsService.getBuildingsByNumber(number);
        }
        if (dataType.equals(FxfzConstants.CZT_GCJZW_INFO)) {
            res = fshBuildingsService.queryFshBuildingsById(dataId);
        }
        if (dataType.equals(FxfzConstants.CZT_ZHJG_INFO)) {
            res = pobStructureService.getById(dataId);
        }
        if (dataType.equals(FxfzConstants.CZT_GJHNT_INFO)) {
            res = RestResponse.succeed(srcAnalyseService.queryResult(dataId));
        }
        assert res != null;
        return RestResponse.succeed(res.getData());
    }

    @Override
    public RestResponse moveBasicLibrary(CustomVulnerabilityParam param) {
        try {
            if(param.getProvince().equals("-")){
                return RestResponse.fail("失败,区域信息不全的不允许移入基础库!");
            }
            if (param.getOperate().equals("0")) {
                svAnalysisRepository.moveBasicLibraryById(param.getId(), param.getOperate());
            } else {
                Integer count = customVulnerabilityRepository.queryBasicLibrary(param);
                if (count != 0) {
                    return RestResponse.fail("失败,存在重复数据!");
                } else {
                    svAnalysisRepository.moveBasicLibraryById(param.getId(), param.getOperate());
                }
            }
            return RestResponse.succeed("成功!");
        } catch (Exception e) {
            String errorMessage = "失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public void generatedExportMatrix(HttpServletResponse response, String matrixId) {
        CztBuildingMatrixEntity cztBuildingMatrixEntity = svAnalysisRepository.getBuildingMatrixById(matrixId);
        String spilt = spilt(cztBuildingMatrixEntity.getDataSourcesIds());
        String[] intensityArr = {"6度", "7度", "8度", "9度", "10度"};
        List<GenerateVulnerabilityMatrixVo> dataList = new ArrayList<>();
        //震害数据矩阵
        if (cztBuildingMatrixEntity.getMatrixType() == 1) {
            dataList = getDataList(spilt, intensityArr);
        }
        // 2 预测数据矩阵  3 筛选数据矩阵
        if (cztBuildingMatrixEntity.getMatrixType() == 2 || cztBuildingMatrixEntity.getMatrixType() == 3) {
            dataList = getPredictiveData(spilt, intensityArr, cztBuildingMatrixEntity.getMatrixType());
        }
        exportMatrixUtil(response, dataList);
    }

    @Override
    public RestResponse deleteBasicLibrary(String ids) {
        try {
            for (String id : ids.split(",")) {
                svAnalysisRepository.deleteBasicLibrary(id);
            }
            return RestResponse.succeed("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage());
            return RestResponse.fail("删除失败!");
        }
    }

    private static final String GC = "GC";
    private static final String GH = "GH";
    private static final String ZH = "ZH";

    @Override
    public RestResponse recalculate(HashMap<String, String> map) {
        try {
            RestResponse response = null;
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (key.equals(GC)) {
                    ModelCalculationParam param = new ModelCalculationParam();
                    param.setChbpiIds(value);
                    //后台计算只需要id，其他参数用不到
                    response = fshBuildingsService.modelCalculation(param);
                } else if (key.equals(GH)) {
                    srcAnalyseService.reCalculates(value);
                    response = RestResponse.succeed("重新计算成功！");
                } else if (key.equals(ZH)) {
                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("ids", value);
                    response = pobStructureService.countPobStructure(paramMap);
                }
            }
            return response;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
